package com.longge;

public class SearchRange {

    public int[] searchRange(int[] nums, int target) {

        return new int[]{findLeft(nums, target), fidRight(nums, target)};
    }

    private int findLeft(int[] nums, int target) {
        int l = 0, r = nums.length - 1;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            if (nums[mid] == target) {
                r = mid - 1;
            } else if (nums[mid] < target) {
                l = mid + 1;
            } else if (nums[mid] > target) {
                r = mid - 1;
            }
        }
        if (r == nums.length - 1) return -1;
        return nums[r + 1] == target ? r + 1 : -1;

    }

    private int fidRight(int[] nums, int target) {

        int l = 0, r = nums.length - 1;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            if (nums[mid] == target) {
                l = mid + 1;
            } else if (nums[mid] < target) {
                l = mid + 1;
            } else if (nums[mid] > target) {
                r = mid - 1;
            }
        }
        if (r < 0) return -1;
        return nums[r] == target ? r : -1;
    }
}
